package com.furnitur.modules.admin.controller.statistics;

import com.furnitur.common.api.CommonResult;
import com.furnitur.common.exception.BusinessException;
import com.furnitur.modules.admin.dto.statistics.DashboardStatisticsDTO;
import com.furnitur.modules.admin.service.statistics.DashboardService;
import com.furnitur.modules.admin.vo.statistics.DashboardStatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;

@Slf4j
@RestController
@RequestMapping("/api/dashboard")
public class DashboardController {

    @Autowired
    private DashboardService dashboardService;

    @GetMapping("/statistics")
    public CommonResult<DashboardStatisticsVO> getStatistics(
            @RequestParam(required = false) String timeUnit,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        log.info("Getting dashboard statistics - timeUnit: {}, startDate: {}, endDate: {}", 
                timeUnit, startDate, endDate);
        
        DashboardStatisticsDTO dto = new DashboardStatisticsDTO();
        dto.setTimeUnit(timeUnit);
        
        // 日期转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (startDate != null) {
                dto.setStartDate(sdf.parse(startDate));
            }
            if (endDate != null) {
                dto.setEndDate(sdf.parse(endDate));
            }
        } catch (ParseException e) {
            log.error("Date parse error", e);
            return CommonResult.failed("日期格式错误");
        }
        
        try {
            DashboardStatisticsVO statistics = dashboardService.getStatistics(dto);
            return CommonResult.success(statistics);
        } catch (BusinessException e) {
            log.error("Get dashboard statistics failed", e);
            return CommonResult.failed(e.getMessage());
        }
    }
} 